package com.xuxin.pda.activity;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.zyapi.pos.PosManager;
import android.zyapi.pos.PrinterDevice;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.xuxin.pda.R;
import com.xuxin.pda.base.BaseConstant;
import com.xuxin.pda.base.BasePDAActivity;
import com.xuxin.pda.bean.CompanyBean;
import com.xuxin.pda.bean.TrashExitBean;
import com.xuxin.pda.bean.TrashTypeBean;
import com.xuxin.pda.bean.WarehouseBean;
import com.xuxin.pda.contract.TrashExitContract;
import com.xuxin.pda.listener.PrinterListener;
import com.xuxin.pda.popup.ConfirmPopup;
import com.xuxin.pda.presenter.TrashExitPresenter;
import com.xuxin.pda.utils.ACache;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xu_xin
 * Created on 2021/2/3 0003
 * 医废出库
 */
public class TrashExitActivity extends BasePDAActivity implements TrashExitContract.View {
    private final TrashExitContract.Presenter presenter = new TrashExitPresenter(this);
    @BindView(R.id.title_name)
    TextView title_name;
    @BindView(R.id.title_left)
    ImageView title_left;
    @BindView(R.id.title_right)
    ImageView title_right;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.trash_exit_user)
    TextView trash_exit_user;
    @BindView(R.id.trash_exit_company)
    TextView trash_exit_company;
    @BindView(R.id.trash_exit_house)
    TextView trash_exit_house;

    private String userName;//用户名
    private String TransferCompanyName;//转运公司
    private String WarehouseId;//库号
    private String InWarehouseTime;//入库时间
    private String userId;//用户id
    private String trashID;//医废袋id
    private String trashWeight;
    private String message;
    private double totalWeight;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_trash_exit);
    }

    @Override
    public void initView() {
        title_name.setText("医废出库");
        button.setText("确认出库");
        title_right.setVisibility(View.INVISIBLE);
    }

    @Override
    public void initData() {
        initPrint();
        ACache aCache = ACache.get(context);
        userId = aCache.getAsString(BaseConstant.userId);
        userName = aCache.getAsString(BaseConstant.userName);
        trash_exit_user.setText(userName);
        handler.sendEmptyMessage(2);
    }

    @Override
    public void onComplete() {
        dismiss();
    }

    @Override
    @OnClick({R.id.title_left, R.id.button, R.id.trash_exit_company})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.title_left) {
            finish();
        } else if (id == R.id.trash_exit_company) {
            if (null != companyList) {
                new XPopup.Builder(context)
                        .maxWidth((int) (ScreenUtils.getScreenWidth() * 0.65))
                        .asCenterList("请选择医废处置公司", companyList, null, 0,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        trash_exit_company.setText(text);
                                    }
                                }, R.layout.popup_list, R.layout.popup_list_item)
                        .show();
            }

        } else if (id == R.id.button) {
            TransferCompanyName = trash_exit_company.getText().toString();
            if (StringUtils.isEmpty(TransferCompanyName)) {
                ToastUtils.showShort("请填写转运公司信息");
                return;
            }
            if (StringUtils.isEmpty(WarehouseId)) {
                ToastUtils.showShort("请扫描库房二维码");
                return;
            }
            if (StringUtils.isEmpty(message)) {
                ToastUtils.showShort("请重新扫描库房二维码");
                return;
            }
            if (totalWeight <= 0) {
                ToastUtils.showShort("暂无可回收医废");
                return;
            }
            new XPopup.Builder(context)
                    .dismissOnTouchOutside(true)
                    .dismissOnBackPressed(true)
                    .asCustom(new ConfirmPopup(context, "确定要出库吗？", new ConfirmPopup.OnConfirmListener() {
                        @Override
                        public void onConfirm() {
                            popup.setTitle("正在出库中...").show();
                            handler.sendEmptyMessageDelayed(1, 500);
                        }
                    })).show();
        }
    }


    @Override
    public void onSuccess(WarehouseBean warehouseBean) {
        if (null != warehouseBean && null != warehouseBean.getResult() && null != warehouseBean.getResult().getInfos()) {
            totalWeight = warehouseBean.getResult().getTotalweight();
            message = "总重量：" + warehouseBean.getResult().getTotalweight() + "kg" + "\n";
            for (int i = 0; i < warehouseBean.getResult().getInfos().size(); i++) {
                message = message + warehouseBean.getResult().getInfos().get(i).getCategoryName() + "：" + warehouseBean.getResult().getInfos().get(i).getWeight() + "\n";
            }
            trash_exit_house.setText(message);
        }
    }

    @Override
    public void onSuccess(TrashExitBean trashExitBean) {
        ToastUtils.showShort("出库成功");
        print(trashExitBean.getResult().getMessage());
        message = "";
    }
    private String[] companyList;
    @Override
    public void onSuccess(CompanyBean companyBean) {
        if (null != companyBean && null != companyBean.getResult()) {
            companyList = new String[companyBean.getResult().getItems().size()];
            for (int i = 0; i < companyBean.getResult().getItems().size(); i++) {
                companyList[i] = companyBean.getResult().getItems().get(i).getCompanyName();
            }
        }
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 0) {
                presenter.GetWarehouseInfo(WarehouseId);
            } else if (msg.what == 1) {
                String messages = "转运公司：" + TransferCompanyName + "\n" + "出库人员：" + userName + "\n" + message;
                presenter.trashExit(TransferCompanyName, WarehouseId, userId, messages);
            } else if (msg.what == 2) {
                presenter.GetCompany();
            }
            return false;
        }
    });

    @Override
    public void onPDASuccess(String message) {
        LogUtils.e("message = " + message);
        if (message.startsWith("WHS") && !StringUtils.isEmpty(message)) {
            WarehouseId = message;
            handler.sendEmptyMessage(0);
        } else {
            ToastUtils.showShort("二维码格式错误");
        }
    }

    /**
     * 初始化打印
     */
    private PrinterDevice mPrinter = null;

    private void initPrint() {
        mPrinter = PosManager.get().getPrinterDevice();
        mPrinter.setPrintEventListener(new PrinterListener());
        mPrinter.init();
    }

    /**
     * 开始打印
     */
    private void print(String message) {
        if (mPrinter.isPrinting()) {
            ToastUtils.showShort("正在打印中，请稍后...");
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("无锡明慈医院");
        sb.append("\n");
        sb.append("(出库汇总)");
        sb.append("\n\n");
        PrinterDevice.TextData title = mPrinter.new TextData();
        mPrinter.addText(25, sb.toString());

        sb = new StringBuilder();
        sb.append(message);
        sb.append("\n");
        PrinterDevice.TextData tData = mPrinter.new TextData();
        tData.addText(sb.toString());
        mPrinter.addText(25, tData);
        sb = new StringBuilder();

        String time = TimeUtils.getNowString(TimeUtils.getSafeDateFormat("yyyy-MM-dd HH:mm"));
        sb.append("出库时间：").append(time);
        sb.append("\n\n\n\n\n");
        sb.append("\n");
        tData = mPrinter.new TextData();
        tData.addText(sb.toString());
        mPrinter.addText(25, tData);
        mPrinter.printStart();
    }
}